# Copyright 2021 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
""" MindVison Classification evaluation script. """

from mindspore import context
from mindspore.train import Model
from mindspore.train.serialization import load_checkpoint, load_param_into_net
from mindspore.nn.metrics import Accuracy
from mindspore._checkparam import Validator, Rel

from utils import get_config, parse_args
from dataset.base_dataset import create_dataset
from models.build_train import build_model
from models.loss import create_loss
from models.optimizer import create_optimizer


def main(pargs):
    # set config context
    config = get_config(pargs.config, overrides=pargs.override)
    context.set_context(mode=context.GRAPH_MODE,
                        device_target=config.device_target)

    # perpare dataset
    dataset_eval = create_dataset(config, states="eval")
    number = Validator.check_int(dataset_eval.get_dataset_size(), 0, Rel.GT)

    # set network, loss, optimizer
    network = build_model(config)
    network_loss = create_loss(config)
    network_opt = create_optimizer(network.trainable_params(), config)

    # load pretrain model
    param_dict = load_checkpoint(config.pretrained_model)
    load_param_into_net(network, param_dict)

    # init the whole Model
    model = Model(network,
                  network_loss,
                  network_opt,
                  metrics={"Accuracy": Accuracy()})

    # begin to train
    print(f'[Start eval `{config.model_name}`]')
    print("="*80)
    acc = model.eval(dataset_eval)
    print("============== {} ================".format(acc))
    print(f'[End of eval `{config.model_name}`]')


if __name__ == '__main__':
    args = parse_args()
    main(args)

